<template>
	<a-modal title="编辑BOM" :width="1500" :visible="visible" :maskClosable="false" :confirmLoading="confirmLoading"
		:footer="disabled ? null : undefined" @ok="handleSubmit" @cancel="handleCancel">

		<a-spin :spinning="confirmLoading">
			<a-form :form="form">
				<a-row>
					<a-col :span="12">
						<a-form-item style="display: none;" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input :disabled="disabled" v-decorator="['bomId']" />
						</a-form-item>
					</a-col>

					<a-col :span="12" v-show="false">
						<a-form-item label="主键" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入主键" :disabled="disabled"
								v-decorator="['bomId', { rules: [{ required: true, message: '请输入主键！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item v-show="false" label="父id" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入父id" :disabled="disabled"
								v-decorator="['pid', { rules: [{ required: true, message: '请输入父id！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="24">
						<a-form-item label="BOM名称" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入BOM名称" :disabled="disabled"
								v-decorator="['bomName', { rules: [{ required: true, message: '请输入BOM名称！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item label="BOM编码" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入BOM编码" :disabled="disabled"
								v-decorator="['bomCode', { rules: [{ required: true, message: '请输入BOM编码！' }] }]" />
						</a-form-item>
					</a-col>


					<a-col :span="12" v-show="false">
						<a-form-item label="BOM类型" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入类型" :disabled="disabled"
								v-decorator="['bomType', { rules: [{ required: true, message: '请输入类型！' }] }]" />
						</a-form-item>
					</a-col>


					<a-col :span="12">
						<a-form-item label="BOM分类" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<!--              <a-input placeholder="请输入分类" :disabled="disabled" v-decorator="['bomClass', {rules: [{required: true, message: '请输入分类！'}]}]"/>-->
							<a-select placeholder="请输入BOM分类"
								v-decorator="['bomClass', { rules: [{ required: true, message: '请输入BOM分类！' }] }]" :disabled="disabled">
								<a-select-option :value="value" v-for="{ value, label } in bomClassArray">
									{{ label }}
								</a-select-option>
							</a-select>
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item label="状态" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-radio-group style="width: 100%;" :disabled="disabled"
								v-decorator="['isDisable', { rules: [{ required: true, message: '请选择状态！' }] }]">
								<a-radio :value="1">
									正常
								</a-radio>
								<a-radio :value="2">
									停用
								</a-radio>
							</a-radio-group>
						</a-form-item>
					</a-col>

					<a-col :span="24">
						<a-form-item label="图片" :labelCol="labelColBlock" :wrapperCol="wrapperColBlock" has-feedback="">
							<a-input placeholder="请输入图片" v-show="false" :disabled="disabled"
								v-decorator="['image', { rules: [{ required: true, message: '请输入图片！' }] }]" />
							<fc-upload :file-list="uploadFileList" :disabled="disabled"
								:handle-file-list-string-change="handleFileListStringChange" />
							<!-- <CropperUpload
                :file-list="uploadFileList"
                :disabled="disabled"
                @fcsuccess="fcsuccess"
                avatarText=""
              /> -->
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item v-show="false" label="创建时间" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入创建时间" :disabled="disabled"
								v-decorator="['createTime', { rules: [{ required: false, message: '请输入创建时间！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item v-show="false" label="创建人" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入创建人" :disabled="disabled"
								v-decorator="['createUser', { rules: [{ required: false, message: '请输入创建人！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item v-show="false" label="更新时间" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入更新时间" :disabled="disabled"
								v-decorator="['updateTime', { rules: [{ required: false, message: '请输入更新时间！' }] }]" />
						</a-form-item>
					</a-col>

					<a-col :span="12">
						<a-form-item v-show="false" label="更新人" :labelCol="labelCol" :wrapperCol="wrapperCol" has-feedback="">
							<a-input placeholder="请输入更新人" :disabled="disabled"
								v-decorator="['updateUser', { rules: [{ required: false, message: '请输入更新人！' }] }]" />
						</a-form-item>
					</a-col>

					<!--        自身BOM Table组件   -->
					<a-col :span="24">
						<a-form-item :validate-status="bomSelfValidate.validateStatus" :help="bomSelfValidate.errorMsg">
							<!--        复杂的BOM Table组件   -->
							<FCBomMaterialTable ref="bomMaterialTableSelf" :default-bom="bom" :readonly="disabled"
								:isPermission="managerOrFinance()" :allow-delete-bom="false" />
						</a-form-item>
					</a-col>

					<!--    引入别的BOM    -->
					<a-col :span="24" v-if="!disabled && form.getFieldValue('bomType') == 2">
						<a-form-item>
							<a-button type="primary" @click="() => { this.bomIndexVisible = true; this.$refs.emsBomIndex1.show() }">
								引入其它BOM
							</a-button>
							<ems-bom-index1 ref="emsBomIndex1" :ok="onBomSelected" />
						</a-form-item>
					</a-col>

					<!--        其它BOM Table组件   -->
					<a-col :span="24">
						<a-form-item v-for="(item, index) in otherBoms">
							<FCBomMaterialTable :ref="'bomMaterialTable' + index" :key="index"
								@delete="(key) => otherBoms.splice(key, 1)" :default-bom="item" :readonly="disabled"
								:isPermission="managerOrFinance()" />
						</a-form-item>
					</a-col>
				</a-row>
			</a-form>
		</a-spin>
	</a-modal>
</template>

<script>
import { detailFull, edit } from '@/api/modular/main/emsbom/emsBomManage'
import { listFull as emsBomMaterialListFull } from '@/api/modular/main/emsbommaterial/emsBomMaterialManage'
import emsBomIndex1 from './emsBomIndex1'
import FcUpload from '@/components/FCUpload/FcUpload'
import FCBomMaterialTable from '@/views/main/emsbom/FCBomMaterialTable'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { sysDictDataList } from '@/api/modular/main/emssysdictdata/emsDictDataManage'
import { DICT_TYPE_ID_FOR_BOM_CLASS } from '@/utils/util'

export default {
	components: {
		FCBomMaterialTable,
		FcUpload,
		emsBomIndex1
	},
	data() {
		return {
			labelCol: {
				xs: { span: 24 },
				sm: { span: 6 }
			},
			wrapperCol: {
				xs: { span: 24 },
				sm: { span: 15 }
			},
			labelColBlock: {
				xs: { span: 24 },
				sm: { span: 3 }
			},
			wrapperColBlock: {
				xs: { span: 24 },
				sm: { span: 20 }
			},
			visible: false,
			disabled: false,
			confirmLoading: false,
			form: this.$form.createForm(this),
			bomIndexVisible: false,
			bomClassArray: [],
			uploadFileList: [],
			//  table 组件
			materialTypeList: [
				{ key: 0, name: '原料' }, { key: 1, name: '线缆' }, { key: 2, name: '包材' },
			],

			bom: {
				bomId: '',
				bomCode: '',
				bomName: '本次BOM',
				bomType: '',
				status: '',
				image: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
				bomMaterials: [],
				otherBoms: [],
			},
			bomMaterial: {
				bomMaterialId: '',
				bomId: '',
				bomIdSource: '',
				bomMaterialSort: '',
				materialId: '',
				materialNumber: '',
				createTime: '',
				createUser: '',
				updateTime: '',
				updateUser: '',
			},
			bomSelfValidate: {},
			otherBoms: [],
			selfBoms: []
		}
	},
	methods: {
		fcsuccess(url) {
			this.form.setFieldsValue({ image: url })
		},
		readonly(record) {
			this.edit(record)
			this.disabled = true
		},
		edit(record) {
			this.visible = true
			this.disabled = false

			setTimeout(() => {
				this.form.setFieldsValue(record)
				// 还需要将数据中的图片格式化
				const token = Vue.ls.get(ACCESS_TOKEN)
				this.uploadFileList = record.image.split(',').map(fileID => {
					return {
						uid: fileID,
						name: fileID,
						status: 'done',
						url: `${this.$store.state.baseUrl}/sysFileInfo/preview?id=${fileID}&token=${token}`,
						fileID: fileID
					}
				})
				this.getBomClass()
			}, 100)
			detailFull({ bomId: record.bomId }).then(res => {
				console.log(`detailFull; bom=${JSON.stringify(res.data)}`)
				this.bom = res.data
				this.otherBoms = this.bom.otherBoms
			})
		},
		handleSubmit() {
			this.getSelfBomMaterialValue()
			const { form: { validateFields } } = this
			this.confirmLoading = true

			validateFields((errors, values) => {
				if (!errors) {
					values = Object.assign({ bomMaterials: this.selfBoms, otherBoms: this.otherBoms }, values)
					edit(values).then((res) => {
						this.confirmLoading = false
						if (res.success) {
							this.$message.success('编辑成功')
							this.handleCancel()
							this.$emit('ok', values)
						} else {
							this.$message.info('编辑失败：' + res.message)
						}
					}).finally((res) => {
						this.confirmLoading = false
					})
				} else {
					this.confirmLoading = false
				}
			})
		},
		handleCancel() {
			this.form.resetFields()
			this.visible = false
		},

		// upload
		handleFileListStringChange(fileListString) {
			this.form.setFieldsValue({ image: fileListString })
		},
		getBomClass() {
			sysDictDataList({ typeId: DICT_TYPE_ID_FOR_BOM_CLASS, pageSize: 999 }).then((res) => {
				let dictDataList = res.data
				let bomClassArray = dictDataList.map((dictData) => {
					return {
						value: dictData.id,
						label: dictData.value
					}
				})
				this.bomClassArray = bomClassArray
			})
		},

		// bom
		onBomSelected(selectedBomArray) {
			console.log(`selectedBomArray:${JSON.stringify(selectedBomArray)}`)
			// 新增其它BOM,生成表格控件。数据结构为 bom，其中还需要建立关联的原料数组。
			// 同时还需要处理该BOM引用了多个原料或别的BOM的情况
			// // 表格里面显示BOM中包含的原料列表
			// 不管是普通BOM，还是组合BOM。都将引用的BOM中的原料放进同一张表中
			// 构建BOM数据
			if (selectedBomArray.length == 0) {
				this.$message.error('没有选择BOM')
				return
			}
			if (selectedBomArray.length > 1) {
				this.$message.error('暂不支持多选BOM添加')
				return
			}
			if (selectedBomArray.length > 0) {
				let selectedBom = selectedBomArray[0]
				let bomId = selectedBom.bomId
				emsBomMaterialListFull({ bomId }).then(res => {
					let bomMaterials = res.data
					// 构建BOM Bean
					selectedBom.bomMaterials = bomMaterials
					this.otherBoms.push(selectedBom)
				})
			}
		},
		getSelfBomMaterialValue() {
			// debugger
			let tableValue = this.$refs.bomMaterialTableSelf.getTableValue()
			this.selfBoms = tableValue

			if (tableValue && tableValue.length > 0) {
				this.bomSelfValidate = {
					validateStatus: 'success',
					errorMsg: null,
				}
			} else {
				this.bomSelfValidate = {
					validateStatus: 'error',
					errorMsg: '物料清单不能为空',
				}
			}

			this.getBomTableValue()
		},
		getBomTableValue() {
			// bomMaterialTable
			// debugger
			for (let i = 0; i < this.otherBoms.length; i++) {
				let $refTable = this.$refs['bomMaterialTable' + i][0]
				this.otherBoms[i] = $refTable.getBom()
			}
			// for (const refsKey in this.$refs) {
			//   if (refsKey.startsWith('bomMaterialTable')) {
			//     let $refTable = this.$refs[refsKey]
			//     this.otherBoms.push($refTable.getTableValue())
			//   }
			// }
		}
	}
}
</script>
